<template>
  <a-drawer
    style="z-index: 999"
    height="100%"
    popup-container=".table-page-body"
    v-model:visible="props.visible"
    :placement="props.position"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
    ok-text="保存"
    cancel-text="关闭"
  >
    <template #title>
      {{ props.title }}
    </template>
    <div v-loading="loading">
      <div class="drawer-header">
        <a-form ref="formRef" :model="drawerForm" size="mini" :rules="formRules">
          <a-row :gutter="16">
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="公司" field="firmId">
                <a-cascader
                  v-model="drawerForm.firmId"
                  :options="props.data.firmOptions"
                  allow-clear
                  class="bacClass"
                  style="width: 250px"
                  @change="handleFirmChange"
                  popup-container="html"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="仓库" field="warehouseName">
                <a-select
                  popup-container="html"
                  class="bacClass"
                  style="width: 250px"
                  :filter-option="false"
                  allow-search
                  :options="drawerForm.warehouseNameList"
                  v-model.trim="drawerForm.warehouseName"
                  @click="warehouseSearchs"
                  @change="warehouseChange"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="客户名称" field="customerName">
                <a-select
                  popup-container="html"
                  :loading="selectLoading"
                  class="bacClass"
                  style="width: 250px"
                  :filter-option="false"
                  allow-search
                  :options="drawerForm.customerNameList"
                  v-model.trim="drawerForm.customerName"
                  @click="getCustomerData({ brandName: '' })"
                  @search="handleCustomerNameSearch"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="入库单号">
                <a-input
                  allow-clear
                  class="bacClass"
                  style="width: 250px"
                  v-model="drawerForm.stockincode"
                  disabled
                />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label-col-flex="100px" label="入库类型" field="stockInTypeTypeId">
                <a-select
                  popup-container="html"
                  :loading="selectLoading"
                  class="bacClass"
                  :filter-option="false"
                  v-model.trim="drawerForm.stockInTypeTypeId"
                  allow-clear
                >
                  <a-option value="115">成品入库</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="开单人员">
                <a-input
                  allow-clear
                  class="bacClass"
                  style="width: 239px"
                  v-model="drawerForm.kaidanrenyuan"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="开单日期">
                <a-date-picker
                  popup-container="html"
                  allow-clear
                  v-model="drawerForm.kaidanriqi"
                  :style="{ width: '239px' }"
                  class="bacClass"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="来源单号">
                <a-input
                  allow-clear
                  class="bacClass"
                  style="width: 260px"
                  v-model="drawerForm.laiyuandanhao"
                />
              </a-form-item>
            </a-col>
            <a-col :span="4.8">
              <a-form-item label-col-flex="100px" label="备注">
                <a-input
                  allow-clear
                  class="bacClass"
                  style="width: 274px"
                  v-model="drawerForm.remark"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div class="btn-box">
          <el-button type="success" :icon="CirclePlus" @click="addRow">增行</el-button>
          <el-button :icon="Delete" @click="deleteRow">删除</el-button>
        </div>
      </div>
      <div :style="{ height: tableHeight }">
        <encapsulation-agrid ref="table1Ref" :configaggrid="configTable"></encapsulation-agrid>
      </div>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
  import { reactive, onMounted, nextTick, watch } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { get, post } from '@/api/http'
  import { CirclePlus, Delete } from '@element-plus/icons-vue'
  import { tableColumns2 } from '../tableConfig/index.ts'
  import _ from 'lodash'
  import dayjs from 'dayjs'
  import { useFinishedProductInstockStore } from '@/store/FinishedProductInstock'
  const store = useFinishedProductInstockStore()
  interface DataProps {
    firmOptions: any[]
    [key: string]: any // 允许data对象有任意其他属性
  }
  const props = defineProps<{
    visible: boolean
    title: string
    position: {
      type: string
      default: 'bottom'
    }
    data: DataProps
  }>()
  const emit = defineEmits(['update:visible', 'getList'])
  const loading = ref<boolean>(false)
  let drawerForm = reactive({
    firmId: '',
    warehouseName: '',
    warehouseNameList: [],
    customerName: '',
    customerNameList: [],
    stockincode: '',
    stockInTypeTypeId: '',
    kaidanrenyuan: '',
    kaidanriqi: dayjs().format('YYYY-MM-DD'),
    laiyuandanhao: '',
    remark: '',
  })
  const formRef = ref<any>(null)
  const formRules = reactive({
    firmId: [{ required: true, message: '请选择公司', trigger: 'change' }],
    warehouseName: [{ required: true, message: '请选择仓库', trigger: 'change' }],
    customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
    stockInTypeTypeId: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  })
  // console.log('props :>> ', props)
  const table1Ref = ref<any>(null)
  let configTable = ref({
    url: '', //接口路径
    queryData: {
      //接口参数
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns2,
  })
  const tableHeight = ref('')
  const computedTableHeight = () => {
    const height: any = document.querySelector('.arco-drawer-body')?.clientHeight
    const headerHeight: any = document.querySelector('.drawer-header')?.clientHeight
    tableHeight.value = `${height - headerHeight - 60}px`
  }
  const throttledResize = _.throttle(computedTableHeight, 200)
  //仓库change事件 获取布笼编号数据 存储在pinia中
  const warehouseChange = async (val: any) => {
    store.warehouseId = val
    await store.getShelveCodeList(val)
  }
  //获取自动生成入库单号
  const getStockInCode = async () => {
    try {
      const res = await post({
        url: 'wms/ProductStockIn/getCodeGenerate',
        data: {},
      })
      if (res.code == 200) {
        drawerForm.stockincode = res.data
      } else {
        Message.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  watch(
    () => props.visible,
    (val) => {
      if (val) {
        if (props.title == '新增入库') {
          //获取自动生成入库单号
          getStockInCode()
        } else if (props.title == '修改') {
          nextTick(() => {
            //回显表格数据
            table1Ref.value.setdataListIterface(props.data.tableData)
            //回显表单数据
            const {
              companyId,
              warehouseId,
              customName,
              stockInCode,
              stockInTypeTypeId,
              stockInDate,
              createName,
              deliveryCode,
              remark,
            } = props.data.searchData
            drawerForm.firmId = companyId
            warehouseSearchs()
            drawerForm.warehouseName = warehouseId
            warehouseChange(warehouseId)
            drawerForm.customerName = customName
            drawerForm.stockincode = stockInCode
            drawerForm.stockInTypeTypeId = stockInTypeTypeId
            drawerForm.kaidanriqi = stockInDate
            drawerForm.kaidanrenyuan = createName
            drawerForm.laiyuandanhao = deliveryCode
            drawerForm.remark = remark
          })
        }
        nextTick(() => {
          //每次打开抽屉都重新计算表格高度
          computedTableHeight()
          window.addEventListener('resize', throttledResize)
        })
      } else {
        window.removeEventListener('resize', throttledResize)
      }
    }
  )
  const handleFirmChange = (val: any) => {
    if (val) {
      warehouseSearchs()
    }else {
      drawerForm.warehouseNameList=[]
      drawerForm.warehouseName=''
    }
  }
  const selectLoading = ref<boolean>(false)
  const warehouseSearchs = () => {
    if (drawerForm.firmId == '') {
      drawerForm.warehouseNameList = []
      Message.warning('请先选择公司')
      return
    }
    selectLoading.value = true
    post({
      url: 'wms/warehouse/getWarehouseByPara',
      data: {
        firmId: drawerForm.firmId,
        virtuallyState: 0,
        warehouseTypeName:'成品仓'
      },
    }).then((res: any) => {
      if (res.code == 200) {
        const cloneData = _.cloneDeep(res.data)
        drawerForm.warehouseNameList = cloneData.map((item: any) => {
          return {
            label: item.warehouseName,
            value: item.value,
          }
        })
      } else {
        Message.error(res.message)
      }
      selectLoading.value = false
    })
  }
  //客户名称下拉框查询
  const getCustomerData = async (val: any) => {
    try {
      const res = await post({
        url: 'product/Brand/getFieldValue',
        data: val,
      })
      const { data, code } = res
      if (code === 200) {
        let dataList: any = []
        data.forEach((o: any) => {
          dataList.push(o['brandName'])
        })
        drawerForm.customerNameList = dataList
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    } catch (e) {
      console.log(e)
    }
  }
  //客户名称模糊搜索
  const handleCustomerNameSearch = (val: any) => {
    getCustomerData({ brandName: val })
  }
  const addRow = () => {
    const curData = table1Ref.value.getListData()
    const newRow = {
      orderCode: '',
      customOrderCode: '',
      circulatCard: '',
      clothCode: '',
      brandName: '',
      colorCode: '',
      colorName: '',
      horseNo: '',
      weight: '',
      shelveCode: '',
      storageName: '',
    }
    curData.push(newRow)
    table1Ref.value.setdataListIterface(curData)
  }
  const deleteRow = () => {
    const curData = table1Ref.value.getListData()
    const selectedRow = table1Ref.value.getSelectedRows()
    if (selectedRow.length == 0) {
      Message.warning('请选择要删除的数据')
      return
    }
    const updatedData = curData.filter((item: any) => !selectedRow.includes(item))
    table1Ref.value.setdataListIterface(updatedData)
  }
  const removeDrawerData = () => {
    drawerForm.firmId = ''
    drawerForm.warehouseName = ''
    drawerForm.warehouseNameList = []
    drawerForm.customerName = ''
    drawerForm.customerNameList = []
    drawerForm.stockincode = ''
    drawerForm.stockInTypeTypeId = ''
    drawerForm.kaidanrenyuan = ''
    drawerForm.kaidanriqi = dayjs().format('YYYY-MM-DD')
    drawerForm.laiyuandanhao = ''
    drawerForm.remark = ''
  }
  const handleOk = async () => {
    const valid = await formRef.value.validate()
    if (valid) return
    const curData = table1Ref.value.getListData()
    if (curData.length == 0) {
      Message.warning('请添加入库数据再进行保存操作')
      return
    }
    const isZeroOrNull = curData.some(
      (item: any) => item.ps == 0 || item.ps == '' || item.zl == 0 || item.zl == ''
    )
    if (isZeroOrNull) {
      Message.warning('请输入匹数和重量')
      return
    }
    try {
      const res = await post({
        url:
          props.title == '新增入库'
            ? 'wms/ProductStockIn/insertList'
            : '/wms/ProductStockIn/updateList',
        data: {
          ProductStockInDetail: curData,
          companyId: drawerForm.firmId,
          warehouseId: drawerForm.warehouseName,
          customName: drawerForm.customerName,
          stockInCode: drawerForm.stockincode,
          stockInTypeTypeId: drawerForm.stockInTypeTypeId,
          createName: drawerForm.kaidanrenyuan,
          stockInDate: drawerForm.kaidanriqi,
          deliveryCode: drawerForm.laiyuandanhao,
          remark: drawerForm.remark,
          id: props.data.searchData.id ? props.data.searchData.id : '',
        },
      })
      if (res.code == 200) {
        Message.success(res.message)
        emit('update:visible', false)
        emit('getList')
        removeDrawerData()
      } else {
        Message.error(res.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const handleCancel = () => {
    emit('update:visible', false)
    removeDrawerData()
  }
</script>

<style lang="scss" scoped>
  .drawer-header {
    height: 75px;
    margin-bottom: 20px;
    .btn-box {
      display: inline-block;
      position: absolute;
      right: 50px;
      top: 50px;
    }
  }
</style>
